import { PageContainer } from '@ant-design/pro-components';
import { useRequest, history } from '@umijs/max';
import useStyles from './style.style';
import { PlusOutlined } from '@ant-design/icons';
import {
  Avatar,
  Button,
  Card,
  Input,
  Modal,
  Row,
  Col,
} from 'antd';
import dayjs from 'dayjs';
import type { FC } from 'react';
import React, { useEffect, useState } from 'react';
import EditorModal from './components/EditorModal';
import type { BasicListItemDataType } from './data';
import {
  addProject,
  queryProjects,
  delProject,
  editProject,
} from './service';

const { Search } = Input;
const Info: FC<{
  title: React.ReactNode;
  value: React.ReactNode;
  bordered?: boolean;
}> = ({ title, value, bordered }) => {
  const { styles } = useStyles();
  return (
    <div className={styles.headerInfo}>
      <span>{title}</span>
      <p>{value}</p>
      {bordered && <em />}
    </div>
  );
};
const CardContent = ({
  data: { version, created_at, updated_at },
}: {
  data: BasicListItemDataType;
}) => {
  const { styles } = useStyles();
  return (
    <div style={{ marginTop: '12px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
        <span style={{ fontSize: '12px', color: '#999' }}>版本</span>
        <span style={{ fontSize: '12px', color: '#666' }}>{version || '0.0.0'}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
        <span style={{ fontSize: '12px', color: '#999' }}>创建时间</span>
        <span style={{ fontSize: '12px', color: '#666' }}>{dayjs(created_at).format('YYYY-MM-DD HH:mm')}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span style={{ fontSize: '12px', color: '#999' }}>更新时间</span>
        <span style={{ fontSize: '12px', color: '#666' }}>{dayjs(updated_at).format('YYYY-MM-DD HH:mm')}</span>
      </div>
    </div>
  );
};
export const BasicList: FC = () => {
  const { styles } = useStyles();
  const [open, setVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<
    Partial<BasicListItemDataType> | undefined
  >(undefined);
  const [allData, setAllData] = useState<any[]>([]);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [loadingMore, setLoadingMore] = useState<boolean>(false);

  const {
    data: listData,
    loading,
    run,
  } = useRequest(queryProjects, {
    manual: true
  });

  useEffect(() => {
    run({ skip: 0, limit: 8 }).then((result) => {
      setAllData(result || []);
      setHasMore((result || []).length === 8);
    });
  }, [])

  const { run: postRun } = useRequest(
    (method, params) => {
      if (method === 'remove') {
        return delProject(params);
      }
      if (method === 'update') {
        const formData = new FormData();
        formData.append('project_id', params?.project_id);
        formData.append('title', params?.title);
        formData.append('description', params?.description);
        if (params?.script_files?.[0]?.originFileObj) {
          formData.append('script_files', params?.script_files?.[0]?.originFileObj);
        }
        return editProject(formData);
      }
      const formData = new FormData();
      formData.append('title', params?.title);
      formData.append('description', params?.description);
      formData.append('script_files', params?.script_files?.[0]?.originFileObj);
      return addProject(formData);
    },
    {
      manual: true,
      onSuccess: (result) => {
        setVisible(false);
        setCurrent(undefined);
        run({ skip: 0, limit: 8 }).then((newResult) => {
          setAllData(newResult || []);
          setHasMore((newResult || []).length === 8);
        });
      },
    },
  );

  const onSearch = (e: any) => {
    run({ search: e }).then((result) => {
      setAllData(result || []);
      setHasMore((result || []).length === 8);
    });
  }

  const loadMore = () => {
    if (!hasMore || loadingMore) return;

    setLoadingMore(true);
    run({ skip: allData.length, limit: 8 }).then((result) => {
      const newData = result || [];
      setAllData(prev => [...prev, ...newData]);
      setHasMore(newData.length === 8);
      setLoadingMore(false);
    }).catch(() => {
      setLoadingMore(false);
    });
  };

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    // 当滚动到底部时加载更多数据
    if (scrollHeight - scrollTop <= clientHeight + 10 && hasMore && !loadingMore) {
      loadMore();
    }
  };

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSize: 6,
    total: listData?.length,
  };

  const showEditModal = (item: BasicListItemDataType) => {
    setVisible(true);
    setCurrent(item);
  };

  const deleteItem = (id: string) => {
    postRun('remove', {
      id,
    });
  };

  const extraContent = (
    <div>
      <Button onClick={() => {
        setVisible(true);
      }}><PlusOutlined /> 新增项目</Button>
      <Search
        className={styles.extraContentSearch}
        placeholder="请输入"
        onSearch={onSearch}
        variant="filled"
      />
    </div>
  );

  const onCancel = () => {
    setVisible(false);
    setCurrent(undefined);
  };

  const handleSubmit = (values: BasicListItemDataType) => {
    const method = values?.project_id ? 'update' : 'add';
    postRun(method, values);
  };

  return (
    <div>
      <PageContainer>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            variant="borderless"
            title="项目列表"
            style={{
              marginTop: 24,
            }}
            styles={{
              body: {
                padding: '0 32px 40px 32px',
                height: 'calc(100vh - 200px)',
                overflow: 'auto',
              },
            }}
            onScroll={handleScroll}
            extra={extraContent}
          >
            {loading ? (
              <div style={{ textAlign: 'center', padding: '50px' }}>加载中...</div>
            ) : (
              <Row gutter={[16, 16]}>
                {(allData || []).map((item: any) => (
                  <Col xs={24} sm={12} md={6} lg={6} xl={6} key={item.id}>
                    <Card
                      hoverable
                      actions={[
                        <Button
                          key="view"
                          type="link"
                          onClick={() => {
                            history.push(`/main?id=${item?.id}`)
                          }}
                        >
                          分镜
                        </Button>,
                        <Button
                          key="edit"
                          type="link"
                          onClick={() => {
                            showEditModal(item);
                          }}
                        >
                          编辑
                        </Button>,
                        <Button
                          key="remove"
                          type="link"
                          danger
                          onClick={() => {
                            Modal.confirm({
                              title: '删除项目',
                              content: '确定删除该项目吗？',
                              okText: '确认',
                              cancelText: '取消',
                              onOk: () => deleteItem(item.id),
                            });
                          }}
                        >
                          删除
                        </Button>,
                      ]}
                    >
                      <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                        <Avatar src={item.logo} shape="square" size={60} />
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: '16px', fontWeight: 500, marginBottom: '4px' }}>
                            {item.title}
                          </div>
                          <div style={{ fontSize: '12px', color: '#999', marginBottom: '8px' }}>
                            {item.description}
                          </div>
                          <CardContent data={item} />
                        </div>
                      </div>
                    </Card>
                  </Col>
                ))}
              </Row>
            )}
            {loadingMore && (
              <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                加载更多...
              </div>
            )}
            {!hasMore && allData.length > 0 && (
              <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                没有更多数据了
              </div>
            )}
          </Card>
        </div>
      </PageContainer>
      <EditorModal
        open={open}
        current={current}
        onCancel={onCancel}
        onSubmit={handleSubmit}
      />
    </div>
  );
};
export default BasicList;
